// 调度器
class Dispatcher {
  handlers: Array<any>
  constructor () {
    this.handlers = []
  }

  listen (handler: any) {
    this.handlers.push(handler)
  }

  emit (...args: any[]) {
    this.handlers.forEach(handler => {
      handler(...args)
    })
  }
}

class AudioManager {
  // 音频需要的变量
  private audioContext: AudioContext // Web Audio API 的核心，代表一个音频处理环境
  private audioSource: AudioBufferSourceNode // 音乐源
  private audioGain: GainNode // 调节音量使用 范围 0~1 浮点数
  private audioAnalyser: AnalyserNode
  private audioBuffer: any // 用来存储有限长度的音频数据

  // 音乐管理需要的变量
  private isPaused: boolean
  private playIndex: number
  private music: any
  private musicList: object[]
  private historys: object[]
  constructor() {
    // 创建 AudioContext
    this.audioContext = new AudioContext()
    this.audioSource = this.audioContext.createBufferSource()
    this.audioGain = this.audioContext.createGain()
    this.audioAnalyser = this.audioContext.createAnalyser()
    this.play_demo()
  }
  async play_demo() {
    if(!this.audioBuffer){
      const response = await fetch('/api/audio/要不要买菜 - 火苗 (Live).ogg');
      this.audioBuffer = response
    }
    const arrayBuffer = await this.audioBuffer.arrayBuffer();
    this.audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer);
    this.audioSource.buffer = this.audioBuffer
    this.audioSource.connect(this.audioContext.destination)
    this.audioSource.start()
    this.audioSource.loop = true
    this.audioContext.suspend()
  }
  async play(music: any) {
    if (!this.audioBuffer) {
      const response = await fetch('/api/audio/' + music.name + '.ogg');
      this.audioBuffer = response
    }
    const arrayBuffer = await this.audioBuffer.arrayBuffer();
    this.audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer);
    this.audioSource.buffer = this.audioBuffer
    this.audioSource.connect(this.audioContext.destination)
    this.audioSource.start()
    this.audioSource.loop = true
    this.audioContext.suspend()
  }

  pause() {
    this.audioSource.stop()
    this.audioContext.suspend()
    this.isPaused = true
  }

  resume() {
    this.audioContext.resume()
    this.isPaused = false
  }

  stop() {
    this.audioSource.stop()
    this.audioContext.suspend()
    this.isPaused = false
  }

  setVolume(volume: number) {
    this.audioGain.gain.value = volume
  }

  getVolume() {
    return this.audioGain.gain.value
  }

  getAudioContext() {
    return this.audioContext
  }

  getAudioAnalyser() {
    return this.audioAnalyser
  }
}
export default AudioManager
